import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'

// 实现路由组件的按需加载(按需加载的模式可以让路由单独打包成一个独立的文件，从而实现按需加载)
const Home = () => import('@/views/home/index.vue')
const Login = () => import('@/views/login/index')

const Layout = () => import('@/views/layout/index')
const Goods = () => import('@/views/goods/index') // 商品详情

const LoginCallback = () => import('@/views/login/callback')// 跳转第三方登录
const Cart = () => import('@/views/cart/index') // 购物车
const Checkout = () => import('@/views/member/checkout')// 订单

const routes = [
  {
    path: '/',
    component: Home, // 主页
    // redirect: '/路由地址'   //默认显示的二级路由地址 (如果子路由 path: '',是空 则默认显示此子路由, 则不需要写redirect:  )
    children: [ // 子路由(二级路由)
      { path: '', component: Layout },
      { path: 'product/:id', component: Goods },
      { path: 'cart', component: Cart },
      { path: 'member/checkout', component: Checkout }
    ]
  },
  { path: '/login', component: Login }, // 登录
  { path: '/login/callback', component: LoginCallback }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 拦截所有的路由跳转，如果没有登录需要跳转到登录页面
  // 所有的以/member开头的路径需要验证
  const token = store.state.user.profile.token
  if (to.path.startsWith('/member') && !token) {
    // 跳转到登录页面 /login?redirecturl=/member/checkout?id=12312
    // 携带redirecturl参数可以在登录页面获取，从而登录成功后跳回之前的页面
    return next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

export default router
